<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Cirpho extends Public_Controller
{
	public $limit = 5; // TODO: PS - Make me a settings option

	public function __construct()
	{
		parent::Public_Controller();
		$this->load->model('cip_categories_m');
		$this->load->model('cip_samples_m');
		$this->load->model('cip_settings_m');
		$this->load->model('cip_servers_m');
		$this->load->model('cip_texts_m');
		$this->load->model('cip_groups_m');
		$this->load->model('cip_statistics_m');
		
		$this->load->helper(array('url'));
		
		$this->config->load('cirpho');
		$this->load->helper('text');
		$this->_uploadPath = FCPATH . $this->config->item('upload_folder');
		$this->_command_folder = $this->config->item('command_folder');
		$this->_path = FCPATH . $this->config->item('files_folder');
		$this->_thumFolderPath = $this->config->item('files_thums_folder');
	}
	public function index(){
		/*
		$out = shell_exec("/usr/bin/match -im1 ".$this->_path."home-2.jpg.pgm -k1 ".$this->_path."home-2.jpg.key -im2 ".$this->_path."home-2_1.jpg.pgm -k2 ".$this->_path."home-2_1.jpg.key >/dev/null 2> /tmp/cirpho123");
		
		//print $out ? $out : join("", file("/tmp/cirpho123"));
		$match = $out ? $out : join("", file("/tmp/cirpho123"));
		echo $match;
		die();
		
		*/
		if ($_REQUEST['image']) {
			// convert the image data from base64
			$imgData = base64_decode($_REQUEST['image']);
			
			// set the image paths
			$fileName = md5(date('Ymdgisu')) . '.jpg';
			//$file = $this->_uploadPath . md5(date('Ymdgisu')) . '.jpg';
			$file = $this->_uploadPath . $fileName;
			//$url = 'http://www.mysite.com' . $file; 
			
			// delete the image if it already exists
			if (file_exists($file)) { unlink($file); }
			
			// write the imgData to the file
			$fp = fopen($file, 'w');
			fwrite($fp, $imgData);
			fclose($fp);
			$categoryId = $_POST['categoryId'];
			if($categoryId == "0"){
				$samples = $this->cip_samples_m->getSamples();
			}else{
				$samples = $this->cip_samples_m->getSamplesByCategory($categoryId);
			}
			$max_width = $this->cip_settings_m->get('max_width');
			$minimum_matching_rate = $this->cip_settings_m->get('minimum_matching_rate');
			$decision_matching_rate = $this->cip_settings_m->get('decision_matching_rate');
			
			system("/usr/bin/convert ".$this->_uploadPath.$fileName." -resize ".$max_width->value." -type Grayscale -depth 8 ".$this->_uploadPath.$fileName.".pgm");
			//system($this->_command_folder.'sift < '.$this->_uploadPath.$fileName.'.pgm >'.$this->_uploadPath.$fileName.'.key 2>/tmp/fasjegjegioag123.tmp');
			$siftOut = shell_exec($this->_command_folder.'sift < '.$this->_uploadPath.$fileName.'.pgm >'.$this->_uploadPath.$fileName.'.key 2>/tmp/siftcirpho123');
			$keyPoint = $siftOut ? $siftOut : join("", file("/tmp/siftcirpho123"));
			//echo $keyPoint;
			//Finding keypoints... 83 keypoints found.
			$keyPoint = str_replace("Finding keypoints...","",$keyPoint);
			$keyPoint = trim(str_replace("keypoints found.","",$keyPoint));
			
			$matches = array();
			foreach ($samples as $sample){
				$out = shell_exec($this->_command_folder."match -im1 ".$this->_path.$sample->image.".pgm -k1 ".$this->_path.$sample->image.".key -im2 ".$this->_uploadPath.$fileName.".pgm -k2 ".$this->_uploadPath.$fileName.".key >/dev/null 2> /tmp/cirpho123");
				$match = $out ? $out : join("", file("/tmp/cirpho123"));
				if(!strpos($match, "Error")){
					$match = str_replace("Found","",$match);
					$match = trim(str_replace("matches.","",$match));
					//echo round(($match/$keyPoint)*100, 0)."<br/>";
					if($minimum_matching_rate->value <= round($match/$keyPoint*100, 0)){
						$matches[] = array(
									'decision_matching_rate' => $decision_matching_rate->value,
									'keypoint' => $keyPoint,
									'match'	 => $match,
									'matchPercent' => round($match/$keyPoint*100, 0),
									'image' => base_url() . $this->_thumFolderPath .$sample->image,
									'groupId' => $sample->group_id,
									'comment' => $sample->comment,
									'url' => $sample->url,
									'comment1' => $sample->comment1,
									'url1' => $sample->url1,
									'comment2' => $sample->comment2,
									'url2' => $sample->url2,
									'title' => $sample->title
									);
					}
					if($decision_matching_rate->value <= round($match/$keyPoint*100, 0)){
						break;
					}
				}
			}
			
			if(file_exists($file)){
				unlink($file);
			}
			if(file_exists($file.".pgm")){
				unlink($file.".pgm");
			}
			if(file_exists($file.".key")){
				unlink($file.".key");
			}
			
			echo json_encode($matches);
		}
	}
	public function category(){
		$categories = $this->cip_categories_m->where('deleted', 0)->order_by('order_number')->get_all();
		$servers = $this->cip_servers_m->order_by('name')->get_all();
		$data = array(
			'category' => $categories,
			'server'   => $servers
		);
		echo json_encode($data);
	}
	public function howtouse(){
		$howToUse = $this->cip_texts_m->get('how_to_use');
		echo json_encode($howToUse);
	}
	public function report(){
		if ($_REQUEST['image']) {
			// convert the image data from base64
			$imgData = base64_decode($_REQUEST['image']);
			
			// set the image paths
			$fileName = md5(date('Ymdgisu')) . '.jpg';
			//$file = $this->_uploadPath . md5(date('Ymdgisu')) . '.jpg';
			$file = $this->_uploadPath . $fileName;
			//$url = 'http://www.mysite.com' . $file; 
			
			// delete the image if it already exists
			if (file_exists($file)) { unlink($file); }
			
			// write the imgData to the file
			$fp = fopen($file, 'w');
			fwrite($fp, $imgData);
			fclose($fp);
			
			$this->load->library('email');

			$contact_email = $this->cip_settings_m->get('contact_email');
			if($contact_email){
				$this->email->from($contact_email->value, 'Cirpho');
				$this->email->to($contact_email->value);
			}else{
				$this->email->from($this->config->item('contact_email'), 'Cirpho');
				$this->email->to($this->config->item('contact_email'));
			}
			
			$this->email->subject('Report not match email');
			$this->email->message('Report not match email.');
			$this->email->attach($file);
			$this->email->send();
			if(file_exists($file)){
				unlink($file);
			}
			echo $this->email->print_debugger();
		}
	}
	public function getsize(){
		$dataArray = array();
		$size = $this->cip_settings_m->get('max_width');
		
		if($size){
			$tok = explode("x",$size->value);
			
			$dataArray['width'] = $tok[0];
			$dataArray['height'] = $tok[1]; 
		}else{
			$dataArray['width'] = 150;
			$dataArray['height'] = 150;
		}
		echo json_encode($dataArray);
	}
	public function redirect($groupId, $linkNum){
				
		if($groupId){
			$group = $this->cip_groups_m->get_by('id', intval($groupId));
			if($group){
				$input = array();
				$input['groupId'] = $groupId;
				$input['match'] = 0;
				$input['linked'] = 1;
				$input['date'] = strtotime(date("Y/m/d"));
				
				$statistic = $this->cip_statistics_m->where('group_id', $groupId)->get_by('date', $input['date']);
				if($statistic){
					 $input['linked'] = $statistic->linked + 1;
					 $input['match'] = $statistic->match;
					 $this->cip_statistics_m->updateLinked($statistic->id, $input);
				}else{
					$id = $this->cip_statistics_m->insert($input);
				}
				if($linkNum == 2 && $group->url1 != null){
					$url = $group->url1;
				}else if($linkNum == 3 && $group->url2 != null){
					$url = $group->url2;
				}else{
					$url = $group->url;
				}
			}else{
				$url = 'http://cirpho.com/intro';
			}
			
		}else{
			$url = 'http://cirpho.com/intro';
		}
		
	?>
	<script type="text/javascript">
		location.href = '<?php echo $url?>';
	</script>
	<?php
	
		
	}
	public function updatematch($groupId){
		if($groupId){
			$group = $this->cip_groups_m->get_by('id', intval($groupId));
			if($group){
				$input = array();
				$input['groupId'] = $groupId;
				$input['match'] = 1;
				$input['linked'] = 0;
				$input['date'] = strtotime(date("Y/m/d"));
			
				$statistic = $this->cip_statistics_m->where('group_id', $groupId)->get_by('date', $input['date']);
				if($statistic){
					$input['linked'] = $statistic->linked;
					$input['match'] = $statistic->match + 1;
					$this->cip_statistics_m->updateMatch($statistic->id, $input);
				}else{
					$id = $this->cip_statistics_m->insert($input);
				}
			}
		}
	}
}
?>